#include "gridpagenumbersystem.h"
#include <QtMath>
#include <QDebug>
#include <QLineF>
GridPageNumberSystem::GridPageNumberSystem()
{
    // 初始化所有预设位置的网格状态为中心位置
    for (auto position : PagePositionSystem::getPresetPositions()) {
        m_gridStates[position] = GridState();  // 默认构造为GridStep::Center
    }
}
void GridPageNumberSystem::setGridState(PagePositionSystem::Position position, const GridState& gridState)
{
    if (!isValidGridState(gridState)) {
        return;
    }
    m_gridStates[position] = gridState;
}
GridPageNumberSystem::GridState GridPageNumberSystem::getGridState(PagePositionSystem::Position position) const
{
    return m_gridStates.value(position, GridState());  // 默认返回中心状态
}
QPointF GridPageNumberSystem::calculateGridPosition(const QRectF& pageRect,
                                                   PagePositionSystem::Position position) const
{
    GridState gridState = getGridState(position);
    return calculateGridPosition(pageRect, position, gridState);
}
QPointF GridPageNumberSystem::calculateGridPosition(const QRectF& pageRect,
                                                   PagePositionSystem::Position position,
                                                   const GridState& gridState) const
{
    // 居中位置特殊处理：水平围绕页面中线调节
    if (position == PagePositionSystem::Position::TopCenter ||
        position == PagePositionSystem::Position::BottomCenter) {
        return calculateCenterConstrainedPosition(pageRect, position, gridState);
    }
    // 四角位置标准处理
    return calculateCornerConstrainedPosition(pageRect, position, gridState);
}
QList<QPointF> GridPageNumberSystem::getReachableGridPoints(const QRectF& pageRect,
                                                          PagePositionSystem::Position position) const
{
    QList<QPointF> gridPoints;
    // 生成3×3网格的所有9个点
    for (int h = -1; h <= 1; ++h) {
        for (int v = -1; v <= 1; ++v) {
            GridState testState;
            testState.horizontalStep = static_cast<GridStep>(h);
            testState.verticalStep = static_cast<GridStep>(v);
            QPointF gridPoint = calculateGridPosition(pageRect, position, testState);
            gridPoints.append(gridPoint);
        }
    }
    return gridPoints;
}
GridPageNumberSystem::GridState GridPageNumberSystem::snapToNearestGrid(const QRectF& pageRect,
                                                                        PagePositionSystem::Position position,
                                                                        const QPointF& pixelPosition) const
{
    GridState nearestState;
    double minDistance = std::numeric_limits<double>::max();
    // 遍历所有可能的网格状态，找到最近的一个
    for (int h = -1; h <= 1; ++h) {
        for (int v = -1; v <= 1; ++v) {
            GridState testState;
            testState.horizontalStep = static_cast<GridStep>(h);
            testState.verticalStep = static_cast<GridStep>(v);
            QPointF gridPoint = calculateGridPosition(pageRect, position, testState);
            double distance = QLineF(pixelPosition, gridPoint).length();
            if (distance < minDistance) {
                minDistance = distance;
                nearestState = testState;
            }
        }
    }
    return nearestState;
}
void GridPageNumberSystem::resetToCenter(PagePositionSystem::Position position)
{
    m_gridStates[position].reset();
}
void GridPageNumberSystem::resetAllToCenter()
{
    for (auto& gridState : m_gridStates) {
        gridState.reset();
    }
}
bool GridPageNumberSystem::isValidGridState(const GridState& gridState)
{
    int h = static_cast<int>(gridState.horizontalStep);
    int v = static_cast<int>(gridState.verticalStep);
    // 检查是否在有效范围内：-1, 0, 1
    return (h >= -1 && h <= 1) && (v >= -1 && v <= 1);
}
double GridPageNumberSystem::gridStepToMillimeters(GridStep step)
{
    return static_cast<int>(step) * GRID_STEP_MM;
}
GridPageNumberSystem::GridStep GridPageNumberSystem::millimetersToGridStep(double mm)
{
    return snapToGridStep(mm);
}
// 私有方法实现
GridPageNumberSystem::GridStep GridPageNumberSystem::snapToGridStep(double mm)
{
    // 将毫米值吸附到最近的网格步进
    double normalizedStep = mm / GRID_STEP_MM;
    int roundedStep = qRound(normalizedStep);
    // 限制在有效范围内
    roundedStep = qBound(-1, roundedStep, 1);
    return static_cast<GridStep>(roundedStep);
}
QPointF GridPageNumberSystem::calculateCenterConstrainedPosition(const QRectF& pageRect,
                                                                PagePositionSystem::Position position,
                                                                const GridState& gridState) const
{
    // 获取系统预设的基础位置
    QPointF basePosition = PagePositionSystem::calculatePosition(pageRect, position);
    // 居中位置特殊处理：水平围绕页面绝对中线调节
    double horizontalOffset = gridStepToMillimeters(gridState.horizontalStep);
    double verticalOffset = gridStepToMillimeters(gridState.verticalStep);
    QPointF adjustedPosition;
    adjustedPosition.setX(pageRect.center().x() + horizontalOffset);  // 围绕页面中心线
    adjustedPosition.setY(basePosition.y() + verticalOffset);         // 垂直基于预设边距
    return adjustedPosition;
}
QPointF GridPageNumberSystem::calculateCornerConstrainedPosition(const QRectF& pageRect,
                                                                PagePositionSystem::Position position,
                                                                const GridState& gridState) const
{
    // 获取系统预设的基础位置
    QPointF basePosition = PagePositionSystem::calculatePosition(pageRect, position);
    // 四角位置标准处理：相对于系统预设边距调节
    QPointF gridOffset = gridState.toMillimeterOffset();
    QPointF adjustedPosition = basePosition + gridOffset;
    return adjustedPosition;
}